{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "ranking_task = mz.tasks.Ranking(losses=mz.losses.RankCrossEntropyLoss(num_neg=10))\n",
    "ranking_task.metrics = [\n",
    "    mz.metrics.NormalizedDiscountedCumulativeGain(k=3),\n",
    "    mz.metrics.NormalizedDiscountedCumulativeGain(k=5),\n",
    "    mz.metrics.MeanAveragePrecision()\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "preprocessor = mz.models.ESIM.get_default_preprocessor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 8763.18it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:03<00:00, 5453.94it/s]\n",
      "Processing text_right with append: 100%|██████████| 18841/18841 [00:00<00:00, 464382.40it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|██████████| 18841/18841 [00:00<00:00, 114943.28it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 75574.17it/s]\n",
      "Processing text_left with extend: 100%|██████████| 2118/2118 [00:00<00:00, 782207.97it/s]\n",
      "Processing text_right with extend: 100%|██████████| 18841/18841 [00:00<00:00, 749249.86it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████| 418401/418401 [00:00<00:00, 3008929.55it/s]\n",
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 10463.76it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:03<00:00, 5391.61it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 139066.12it/s]\n",
      "Processing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 198763.50it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 125212.92it/s]\n",
      "Processing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 739308.91it/s]\n",
      "Processing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 723684.33it/s]\n",
      "Processing length_left with len: 100%|██████████| 2118/2118 [00:00<00:00, 776193.61it/s]\n",
      "Processing length_right with len: 100%|██████████| 18841/18841 [00:00<00:00, 1001557.40it/s]\n",
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 122/122 [00:00<00:00, 10261.40it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 1115/1115 [00:00<00:00, 5508.13it/s]\n",
      "Processing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 157076.85it/s]\n",
      "Processing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 137259.95it/s]\n",
      "Processing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 144220.83it/s]\n",
      "Processing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 217008.09it/s]\n",
      "Processing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 681528.56it/s]\n",
      "Processing length_left with len: 100%|██████████| 122/122 [00:00<00:00, 220372.56it/s]\n",
      "Processing length_right with len: 100%|██████████| 1115/1115 [00:00<00:00, 745282.70it/s]\n",
      "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 237/237 [00:00<00:00, 10501.60it/s]\n",
      "Processing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2300/2300 [00:00<00:00, 5492.96it/s]\n",
      "Processing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 154121.06it/s]\n",
      "Processing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 136152.59it/s]\n",
      "Processing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 156242.80it/s]\n",
      "Processing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 340311.55it/s]\n",
      "Processing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 762661.02it/s]\n",
      "Processing length_left with len: 100%|██████████| 237/237 [00:00<00:00, 370914.20it/s]\n",
      "Processing length_right with len: 100%|██████████| 2300/2300 [00:00<00:00, 871051.85it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'filter_unit': <matchzoo.preprocessors.units.frequency_filter.FrequencyFilter at 0x7f29081202b0>,\n",
       " 'vocab_unit': <matchzoo.preprocessors.units.vocabulary.Vocabulary at 0x7f28a032d400>,\n",
       " 'vocab_size': 30058,\n",
       " 'embedding_input_dim': 30058}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=300)\n",
    "term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=5,\n",
    "    num_neg=10\n",
    ")\n",
    "testset = mz.dataloader.Dataset(\n",
    "    data_pack=test_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "padding_callback = mz.models.ESIM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    batch_size=20,\n",
    "    stage='train',\n",
    "    resample=True,\n",
    "    sort=False,\n",
    "    shuffle=True,\n",
    "    callback=padding_callback\n",
    ")\n",
    "testloader = mz.dataloader.DataLoader(\n",
    "    dataset=testset,\n",
    "    batch_size=20,\n",
    "    stage='dev',\n",
    "    sort=False,\n",
    "    shuffle=False,\n",
    "    callback=padding_callback\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ESIM(\n",
      "  (embedding): Embedding(30058, 300)\n",
      "  (rnn_dropout): RNNDropout(p=0.2, inplace=False)\n",
      "  (input_encoding): StackedBRNN(\n",
      "    (rnns): ModuleList(\n",
      "      (0): LSTM(300, 100, bidirectional=True)\n",
      "    )\n",
      "  )\n",
      "  (attention): BidirectionalAttention()\n",
      "  (projection): Sequential(\n",
      "    (0): Linear(in_features=800, out_features=200, bias=True)\n",
      "    (1): ReLU()\n",
      "  )\n",
      "  (composition): StackedBRNN(\n",
      "    (rnns): ModuleList(\n",
      "      (0): LSTM(200, 100, bidirectional=True)\n",
      "    )\n",
      "  )\n",
      "  (classification): Sequential(\n",
      "    (0): Dropout(p=0.2, inplace=False)\n",
      "    (1): Linear(in_features=800, out_features=200, bias=True)\n",
      "    (2): Tanh()\n",
      "    (3): Dropout(p=0.2, inplace=False)\n",
      "  )\n",
      "  (out): Linear(in_features=200, out_features=1, bias=True)\n",
      ")\n",
      "Trainable params:  9901201\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.ESIM()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "model.params['embedding'] = embedding_matrix\n",
    "model.params['mask_value'] = 0\n",
    "model.params['dropout'] = 0.2\n",
    "model.params['hidden_size'] = 200\n",
    "model.params['lstm_layer'] = 1\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model)\n",
    "print('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adadelta(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=testloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9ad06ab1f5694373851df9ead615dc94",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-255 Loss-1.824]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5725 - normalized_discounted_cumulative_gain@5(0.0): 0.6183 - mean_average_precision(0.0): 0.5764\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ad2927d9475d41e286755e2c2b7f1737",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-510 Loss-0.494]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5458 - normalized_discounted_cumulative_gain@5(0.0): 0.6114 - mean_average_precision(0.0): 0.5602\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d3644ff69ef54db2a029fe216af499cf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-765 Loss-0.111]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5442 - normalized_discounted_cumulative_gain@5(0.0): 0.589 - mean_average_precision(0.0): 0.5456\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fbbdee5e914c4226909550e0f1c44cde",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1020 Loss-0.060]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5198 - normalized_discounted_cumulative_gain@5(0.0): 0.5767 - mean_average_precision(0.0): 0.537\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d812252969fb443999188b58fa7482e9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1275 Loss-0.056]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5136 - normalized_discounted_cumulative_gain@5(0.0): 0.5721 - mean_average_precision(0.0): 0.5278\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "74a70a17a12e4020b3d79ad207c83849",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1530 Loss-0.039]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5324 - normalized_discounted_cumulative_gain@5(0.0): 0.5721 - mean_average_precision(0.0): 0.5429\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3589e2f9749a42d3b19df1cf3b8eb243",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1785 Loss-0.017]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5197 - normalized_discounted_cumulative_gain@5(0.0): 0.5838 - mean_average_precision(0.0): 0.54\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3a77ddc745554ef7a55e9c6752f023ab",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2040 Loss-0.020]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5271 - normalized_discounted_cumulative_gain@5(0.0): 0.5819 - mean_average_precision(0.0): 0.5432\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5320925bcc124f2cab16e455f9d04b54",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2295 Loss-0.018]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5122 - normalized_discounted_cumulative_gain@5(0.0): 0.5657 - mean_average_precision(0.0): 0.5277\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d20ef19ed6cf4d458e712f31a556e004",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=255), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2550 Loss-0.018]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.5214 - normalized_discounted_cumulative_gain@5(0.0): 0.5742 - mean_average_precision(0.0): 0.5381\n",
      "\n",
      "Cost time: 9662.94213104248s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
